package com.cardone.common.router.support;

import java.util.Map;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import org.apache.commons.collections.MapUtils;
import org.springframework.cache.annotation.Cacheable;

import com.cardone.common.cache.Caches;
import com.cardone.common.template.util.TemplateUtils;
import com.cardone.common.util.StringUtils;
import com.google.common.collect.Lists;

/**
 * 路由键名
 *
 * @author yaohaitao
 */
@Getter
@Setter
@Accessors(chain = true)
public class RouterKeySimpleSupport implements RouterKeySupport {
	public static void main(final String[] args) {
		System.out.println(StringUtils.getPathForMatch(Lists.newArrayList("com.cardone.*.util.*", "com.cardone.*.util.UserUtils"), "com.cardone.platform.usercenter.util.UserUtils"));
	}

	/**
	 * 默认组标识
	 */
	private String defaultGroupId;

	/**
	 * 默认键名
	 */
	private String defaultKey;

	/**
	 * 表达式路由键名配置
	 */
	private Map<String, Map<String, String>> expressionRouterKeyTable;

	/**
	 * 路由键名配置
	 */
	private Map<String, Map<String, String>> routerKeyTable;

	@Override
	public String readKey(final String value) {
		return this.readKeyByGroupId(null, value, null);
	}

	@Override
	public String readKey(final String value, final Object model) {
		return this.readKeyByGroupId(null, value, model);
	}

	@Override
	@Cacheable(value = RouterKeySupport.BEAN_ID, key = Caches.KEY_3)
	public String readKeyByGroupId(final String groupId, final String value, final Object model) {
		if (!MapUtils.isEmpty(this.expressionRouterKeyTable)) {
			final String newGroupId = StringUtils.defaultIfBlank(groupId, this.defaultGroupId);

			final Map<String, String> expressionRouterKeyMap = this.expressionRouterKeyTable.get(newGroupId);

			if (!MapUtils.isEmpty(expressionRouterKeyMap)) {
				final String path = StringUtils.getPathForMatch(expressionRouterKeyMap.keySet(), value);

				if (org.apache.commons.lang3.StringUtils.isNoneBlank(path)) {
					final String expression = expressionRouterKeyMap.get(path);

					final String key = TemplateUtils.processString(expression, model);

					return StringUtils.defaultIfBlank(key, this.defaultKey);
				}
			}
		}

		if (!MapUtils.isEmpty(this.routerKeyTable)) {
			final String newGroupId = StringUtils.defaultIfBlank(groupId, this.defaultGroupId);

			final Map<String, String> routerKeyMap = this.routerKeyTable.get(newGroupId);

			if (!MapUtils.isEmpty(routerKeyMap)) {
				final String path = StringUtils.getPathForMatch(routerKeyMap.keySet(), value);

				if (org.apache.commons.lang3.StringUtils.isNoneBlank(path)) {
					return StringUtils.defaultIfBlank(routerKeyMap.get(path), this.defaultKey);
				}
			}
		}

		return this.defaultKey;
	}
}